#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
from PIL import Image

def resize_image(image_path, target_size):
    """
    调整图片尺寸到目标大小，保持宽高比
    
    Args:
        image_path: 图片文件路径
        target_size: 目标尺寸元组 (width, height)
    """
    try:
        with Image.open(image_path) as img:
            # 获取原始尺寸
            original_width, original_height = img.size
            
            # 计算缩放比例，保持宽高比
            width_ratio = target_size[0] / original_width
            height_ratio = target_size[1] / original_height
            ratio = min(width_ratio, height_ratio)
            
            # 计算新尺寸
            new_width = int(original_width * ratio)
            new_height = int(original_height * ratio)
            
            # 调整尺寸
            resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
            
            # 创建新画布，将调整后的图片居中放置
            new_img = Image.new('RGB', target_size, (255, 255, 255))
            
            # 计算居中位置
            x_offset = (target_size[0] - new_width) // 2
            y_offset = (target_size[1] - new_height) // 2
            
            # 粘贴调整后的图片
            new_img.paste(resized_img, (x_offset, y_offset))
            
            # 保存图片，覆盖原文件
            new_img.save(image_path)
            print(f"已调整: {image_path} -> {target_size[0]}x{target_size[1]}")
            
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {e}")

def process_directory(directory_path):
    """
    处理指定目录及其子目录中的所有图片文件
    
    Args:
        directory_path: 要处理的目录路径
    """
    # 支持的图片格式
    image_extensions = {'.jpg', '.jpeg', '.png', '.JPG', '.JPEG', '.PNG'}
    
    # 目标尺寸
    target_sizes = [(600, 800), (800, 600)]
    
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            file_ext = os.path.splitext(file)[1].lower()
            if file_ext in image_extensions:
                file_path = os.path.join(root, file)
                
                # 随机选择一个目标尺寸（600x800或800x600）
                target_size = target_sizes[hash(file_path) % len(target_sizes)]
                
                resize_image(file_path, target_size)

def main():
    # 目标目录
    target_directory = r"E:\ejj\ejj_dec"
    
    # 检查目录是否存在
    if not os.path.exists(target_directory):
        print(f"错误: 目录 {target_directory} 不存在")
        sys.exit(1)
    
    if not os.path.isdir(target_directory):
        print(f"错误: {target_directory} 不是一个目录")
        sys.exit(1)
    
    print(f"开始处理目录: {target_directory}")
    print("支持的图片格式: .jpg, .jpeg, .png")
    print("目标尺寸: 600x800 或 800x600")
    print("=" * 50)
    
    # 处理目录
    process_directory(target_directory)
    
    print("=" * 50)
    print("图片处理完成!")

if __name__ == "__main__":
    main()
